<template>
  <div class="admin-stock">
    <el-card>
      <template #header>
        <div class="filter-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称或条形码"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="categoryFilter" placeholder="商品分类" clearable style="width: 150px">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
          
          <el-select v-model="stockFilter" placeholder="库存状态" clearable style="width: 150px">
            <el-option label="全部" :value="null" />
            <el-option label="库存充足" value="sufficient" />
            <el-option label="库存预警" value="warning" />
            <el-option label="库存不足" value="insufficient" />
          </el-select>
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button type="success" @click="showStockRecords">
            <el-icon><Document /></el-icon> 库存记录
          </el-button>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="stockList" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="getImageUrl(row.image)"
              :preview-src-list="[getImageUrl(row.image)]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
              :hide-on-click-modal="true"
            />
            <span v-else style="color: #999;">无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="barcode" label="条形码" width="150" />
        
        <el-table-column prop="stock" label="当前库存" width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="getStockType(row.stock, row.minStock)">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="minStock" label="预警值" width="100" />
        
        <el-table-column label="库存状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStockType(row.stock, row.minStock)">
              {{ getStockStatus(row.stock, row.minStock) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleAdjust(row)">
              <el-icon><Edit /></el-icon> 调整库存
            </el-button>
            <el-button type="success" text @click="handleStockIn(row)">
              <el-icon><Plus /></el-icon> 入库
            </el-button>
            <el-button type="warning" text @click="handleSetMinStock(row)">
              <el-icon><Setting /></el-icon> 设置预警
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: center;"
        @size-change="loadStock"
        @current-change="loadStock"
      />
    </el-card>
    
    <!-- 调整库存对话框 -->
    <el-dialog v-model="adjustDialogVisible" title="调整库存" width="500px">
      <el-form :model="adjustForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ adjustForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span :style="{ color: getStockColor(adjustForm.currentStock, adjustForm.minStock) }">
            {{ adjustForm.currentStock }}
          </span>
        </el-form-item>
        <el-form-item label="预警值">
          <span>{{ adjustForm.minStock }}</span>
        </el-form-item>
        <el-form-item label="调整数量" required>
          <el-input-number 
            v-model="adjustForm.adjustQuantity" 
            :min="-adjustForm.currentStock"
            :step="1"
            style="width: 100%"
          />
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            正数为增加，负数为减少
          </div>
        </el-form-item>
        <el-form-item label="调整后库存">
          <span :style="{ 
            color: getStockColor(adjustForm.currentStock + adjustForm.adjustQuantity, adjustForm.minStock),
            fontSize: '16px',
            fontWeight: 'bold'
          }">
            {{ adjustForm.currentStock + adjustForm.adjustQuantity }}
          </span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="adjustForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入调整原因（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitAdjust"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 入库对话框 -->
    <el-dialog v-model="stockInDialogVisible" title="商品入库" width="500px">
      <el-form :model="stockInForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ stockInForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ stockInForm.currentStock }}</span>
        </el-form-item>
        <el-form-item label="入库数量" required>
          <el-input-number 
            v-model="stockInForm.quantity" 
            :min="1"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="入库后库存">
          <span style="color: #67C23A; fontSize: 16px; fontWeight: bold">
            {{ stockInForm.currentStock + stockInForm.quantity }}
          </span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="stockInForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入入库备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="stockInDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitStockIn"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 设置预警值对话框 -->
    <el-dialog v-model="minStockDialogVisible" title="设置库存预警值" width="500px">
      <el-form :model="minStockForm" label-width="120px">
        <el-form-item label="商品名称">
          <span>{{ minStockForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前预警值">
          <span>{{ minStockForm.currentMinStock }}</span>
        </el-form-item>
        <el-form-item label="新预警值" required>
          <el-input-number 
            v-model="minStockForm.newMinStock" 
            :min="0"
            :step="1"
            style="width: 100%"
          />
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            当库存低于或等于此值时，系统将发出预警提示
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="minStockDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitMinStock"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 库存记录对话框 -->
    <el-dialog v-model="recordDialogVisible" title="库存变动记录" width="1200px">
      <div class="record-filter">
        <el-select v-model="recordFilter.changeType" placeholder="变动类型" clearable style="width: 150px">
          <el-option label="全部" :value="null" />
          <el-option label="入库" value="in" />
          <el-option label="出库" value="out" />
          <el-option label="调整" value="adjust" />
          <el-option label="退货" value="refund" />
        </el-select>
        
        <el-date-picker
          v-model="recordDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 300px"
        />
        
        <el-button type="primary" @click="loadStockRecords">
          <el-icon><Search /></el-icon> 查询
        </el-button>
      </div>
      
      <el-table 
        v-loading="recordLoading" 
        :data="stockRecords" 
        border
        style="margin-top: 15px"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column label="变动类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getChangeTypeTag(row.changeType)">
              {{ row.changeTypeDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="变动数量" width="120">
          <template #default="{ row }">
            <span :style="{ color: row.changeQuantity > 0 ? '#67C23A' : '#F56C6C' }">
              {{ row.changeQuantity > 0 ? '+' : '' }}{{ row.changeQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="beforeStock" label="变动前" width="100" />
        <el-table-column prop="afterStock" label="变动后" width="100" />
        <el-table-column prop="operatorName" label="操作人" width="120" />
        <el-table-column prop="orderNo" label="关联订单" width="180" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="操作时间" width="180" />
      </el-table>
      
      <el-pagination
        v-if="recordTotal > 0"
        v-model:current-page="recordPage"
        v-model:page-size="recordPageSize"
        :total="recordTotal"
        layout="total, prev, pager, next"
        style="margin-top: 20px; justify-content: center;"
        @current-change="loadStockRecords"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Document, Edit, Plus, Setting } from '@element-plus/icons-vue'
import { getProductList } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { adjustStock, stockIn, getStockRecords } from '@/api/stock'
import { updateProduct } from '@/api/product'

const loading = ref(false)
const searchKeyword = ref('')
const categoryFilter = ref(null)
const stockFilter = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const stockList = ref([])
const categories = ref([])
const selectedRows = ref([])

const adjustDialogVisible = ref(false)
const stockInDialogVisible = ref(false)
const recordDialogVisible = ref(false)
const minStockDialogVisible = ref(false)
const submitLoading = ref(false)

const adjustForm = reactive({
  id: null,
  name: '',
  currentStock: 0,
  minStock: 10,
  adjustQuantity: 0,
  remark: ''
})

const stockInForm = reactive({
  id: null,
  name: '',
  currentStock: 0,
  quantity: 1,
  remark: ''
})

const minStockForm = reactive({
  id: null,
  name: '',
  currentMinStock: 10,
  newMinStock: 10
})

const recordFilter = reactive({
  changeType: null
})
const recordDateRange = ref([])
const recordLoading = ref(false)
const recordPage = ref(1)
const recordPageSize = ref(10)
const recordTotal = ref(0)
const stockRecords = ref([])

onMounted(() => {
  loadStock()
  loadCategories()
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadStock = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchKeyword.value,
      categoryId: categoryFilter.value
    }
    
    // 根据库存状态筛选
    if (stockFilter.value === 'warning' || stockFilter.value === 'insufficient') {
      params.stockAlert = true
    }
    
    const res = await getProductList(params)
    if (res.data) {
      let list = res.data.records || []
      
      // 前端过滤库存状态
      if (stockFilter.value === 'sufficient') {
        list = list.filter(item => item.stock > item.minStock)
      } else if (stockFilter.value === 'insufficient') {
        list = list.filter(item => item.stock === 0)
      }
      
      stockList.value = list
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载库存失败:', error)
    ElMessage.error('加载库存数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadStock()
}

const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

const handleAdjust = (row) => {
  adjustForm.id = row.id
  adjustForm.name = row.name
  adjustForm.currentStock = row.stock
  adjustForm.minStock = row.minStock
  adjustForm.adjustQuantity = 0
  adjustForm.remark = ''
  adjustDialogVisible.value = true
}

const handleStockIn = (row) => {
  stockInForm.id = row.id
  stockInForm.name = row.name
  stockInForm.currentStock = row.stock
  stockInForm.quantity = 1
  stockInForm.remark = ''
  stockInDialogVisible.value = true
}

const handleSetMinStock = (row) => {
  minStockForm.id = row.id
  minStockForm.name = row.name
  minStockForm.currentMinStock = row.minStock || 10
  minStockForm.newMinStock = row.minStock || 10
  minStockDialogVisible.value = true
}

const handleSubmitAdjust = async () => {
  if (adjustForm.adjustQuantity === 0) {
    ElMessage.warning('调整数量不能为0')
    return
  }
  
  submitLoading.value = true
  try {
    await adjustStock({
      productId: adjustForm.id,
      adjustQuantity: adjustForm.adjustQuantity,
      remark: adjustForm.remark || '库存调整'
    })
    
    ElMessage.success('库存调整成功')
    adjustDialogVisible.value = false
    loadStock()
  } catch (error) {
    ElMessage.error(error.message || '库存调整失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSubmitStockIn = async () => {
  if (stockInForm.quantity <= 0) {
    ElMessage.warning('入库数量必须大于0')
    return
  }
  
  submitLoading.value = true
  try {
    await stockIn({
      productId: stockInForm.id,
      adjustQuantity: stockInForm.quantity,
      remark: stockInForm.remark || '商品入库'
    })
    
    ElMessage.success('入库成功')
    stockInDialogVisible.value = false
    loadStock()
  } catch (error) {
    ElMessage.error(error.message || '入库失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSubmitMinStock = async () => {
  if (minStockForm.newMinStock < 0) {
    ElMessage.warning('预警值不能为负数')
    return
  }
  
  submitLoading.value = true
  try {
    await updateProduct({
      id: minStockForm.id,
      minStock: minStockForm.newMinStock
    })
    
    ElMessage.success('预警值设置成功')
    minStockDialogVisible.value = false
    loadStock()
  } catch (error) {
    ElMessage.error(error.message || '预警值设置失败')
  } finally {
    submitLoading.value = false
  }
}

const showStockRecords = () => {
  recordDialogVisible.value = true
  recordPage.value = 1
  loadStockRecords()
}

const loadStockRecords = async () => {
  recordLoading.value = true
  try {
    const params = {
      page: recordPage.value,
      pageSize: recordPageSize.value,
      changeType: recordFilter.changeType
    }
    
    if (recordDateRange.value && recordDateRange.value.length === 2) {
      params.startDate = recordDateRange.value[0]
      params.endDate = recordDateRange.value[1]
    }
    
    const res = await getStockRecords(params)
    if (res.data) {
      stockRecords.value = res.data.records || []
      recordTotal.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载库存记录失败:', error)
    ElMessage.error('加载库存记录失败')
  } finally {
    recordLoading.value = false
  }
}

const getStockType = (stock, minStock) => {
  if (stock === 0) return 'danger'
  if (stock <= minStock) return 'warning'
  return 'success'
}

const getStockStatus = (stock, minStock) => {
  if (stock === 0) return '缺货'
  if (stock <= minStock) return '预警'
  return '正常'
}

const getStockColor = (stock, minStock) => {
  if (stock === 0) return '#F56C6C'
  if (stock <= minStock) return '#E6A23C'
  return '#67C23A'
}

const getChangeTypeTag = (type) => {
  const map = {
    'in': 'success',
    'out': 'danger',
    'adjust': 'warning',
    'refund': 'info'
  }
  return map[type] || ''
}

const getImageUrl = (image) => {
  if (!image) return ''
  if (image.startsWith('http://') || image.startsWith('https://')) return image
  // 图片文件直接从后端服务器获取
  return `http://localhost:8080/${image.startsWith('/') ? image.slice(1) : image}`
}
</script>

<style lang="scss" scoped>
.admin-stock {
  .filter-bar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
  
  .record-filter {
    display: flex;
    gap: 10px;
    align-items: center;
  }
}
</style>
